home *** CD-ROM | disk | FTP | other *** search
/ Gigarom 1 / Gigarom Macintosh Archives (Quantum Leap)(CDRM1080320)(1993).iso / FILES / DEV / A-B / 001. Sample.cpt / Sample.c < prev    next >
C/C++ Source or Header  |  1988-08-02  |  26KB  |  764 lines

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple Sample Application
  6. #
  7. #    Sample
  8. #
  9. #    Sample.c    -    C Source
  10. #
  11. #    Copyright © 1988 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:    1.0                    8/88
  15. #
  16. #    Components:    Sample.p            August 1, 1988
  17. #                Sample.c            August 1, 1988
  18. #                Sample.r            August 1, 1988
  19. #                Sample.h            August 1, 1988
  20. #                PSample.make        August 1, 1988
  21. #                CSample.make        August 1, 1988
  22. #
  23. #    Sample is an example application that demonstrates how to
  24. #    initialize the commonly used toolbox managers, operate 
  25. #    successfully under MultiFinder, handle desk accessories, 
  26. #    and create, grow, and zoom windows.
  27. #
  28. #    It does not by any means demonstrate all the techniques 
  29. #    you need for a large application. In particular, Sample 
  30. #    does not cover exception handling, multiple windows/documents, 
  31. #    sophisticated memory management, printing, or undo. All of 
  32. #    these are vital parts of a normal full-sized application.
  33. #
  34. #    This application is an example of the form of a Macintosh 
  35. #    application; it is NOT a template. It is NOT intended to be 
  36. #    used as a foundation for the next world-class, best-selling, 
  37. #    600K application. A stick figure drawing of the human body may 
  38. #    be a good example of the form for a painting, but that does not 
  39. #    mean it should be used as the basis for the next Mona Lisa.
  40. #
  41. #    We recommend that you review this program or TESample before 
  42. #    beginning a new application.
  43. #
  44. ------------------------------------------------------------------------------*/
  45.  
  46.  
  47. /* Segmentation strategy:
  48.  
  49.    This program consists of three segments. Main contains most of the code,
  50.    including the MPW libraries, and the main program. Initialize contains
  51.    code that is only used once, during startup, and can be unloaded after the
  52.    program starts. %A5Init is automatically created by the Linker to initialize
  53.    globals for the MPW libraries and is unloaded right away. */
  54.  
  55.  
  56. /* SetPort strategy:
  57.  
  58.    Toolbox routines do not change the current port. In spite of this, in this
  59.    program we use a strategy of calling SetPort whenever we want to draw or
  60.    make calls which depend on the current port. This makes us less vulnerable
  61.    to bugs in other software which might alter the current port (such as the
  62.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  63.    Hopefully, this also makes the routines from this program more self-contained,
  64.    since they don't depend on the current port setting. */
  65.  
  66.  
  67. #include <Values.h>
  68. #include <Types.h>
  69. #include <Resources.h>
  70. #include <QuickDraw.h>
  71. #include <Fonts.h>
  72. #include <Events.h>
  73. #include <Windows.h>
  74. #include <Menus.h>
  75. #include <TextEdit.h>
  76. #include <Dialogs.h>
  77. #include <Desk.h>
  78. #include <ToolUtils.h>
  79. #include <Memory.h>
  80. #include <SegLoad.h>
  81. #include <Files.h>
  82. #include <OSUtils.h>
  83. #include <Traps.h>        /* MPW 2.0.2 Traps.h is missing an #endif */
  84. #include <Sample.h>        /* bring in all the #defines for Sample */
  85.  
  86.  
  87. /* The "g" prefix is used to emphasize that a variable is global. */
  88.  
  89. /* GMac is used to hold the result of a SysEnvirons call. This makes
  90.    it convenient for any routine to check the environment. */
  91. SysEnvRec    gMac;                /* set up by Initialize */
  92.  
  93. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  94.    trap is available. If it is false, we know that we must call GetNextEvent. */
  95. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  96.  
  97. /* GInBackground is maintained by our osEvent handling routines. Any part of
  98.    the program can check it to find out if it is currently in the background. */
  99. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  100.  
  101.  
  102. /* The following globals are the state of the window. If we supported more than
  103.    one window, they would be attatched to each document, rather than globals. */
  104.  
  105. /* GStopped tells whether the stop light is currently on stop or go. */
  106. Boolean        gStopped;            /* maintained by Initialize and SetLight */
  107.  
  108. /* GStopRect and gGoRect are the rectangles of the two stop lights in the window. */
  109. Rect        gStopRect;            /* set up by Initialize */
  110. Rect        gGoRect;            /* set up by Initialize */
  111.  
  112.  
  113. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  114.    actual prototypes for parameter type checking. */
  115. #ifndef MPW3
  116.     void EventLoop();
  117.     void DoEvent( /* EventRecord *event */ );
  118.     void AdjustCursor( /* Point mouse, RgnHandle region */ );
  119.     void DoUpdate( /* WindowPtr window */ );
  120.     void DoActivate( /* WindowPtr window, Boolean becomingActive */ );
  121.     void DoContentClick( /* WindowPtr window */ );
  122.     void DrawWindow( /* WindowPtr window */ );
  123.     void AdjustMenus();
  124.     void DoMenuCommand( /* long menuResult */ );
  125.     void SetLight( /* WindowPtr window, Boolean newStopped */ );
  126.     void DoCloseWindow( /* WindowPtr window */ );
  127.     void DoCloseBehind( /* WindowPtr window */ );
  128.     void Terminate();
  129.     void Initialize();
  130.     void GoGetRect( /* short rectID, Rect *theRect */ );
  131.     void ForceEnvirons();
  132.     Boolean IsAppWindow( /* WindowPtr window */ );
  133.     Boolean IsDAWindow( /* WindowPtr window */ );
  134.     Boolean TrapAvailable( /* short tNumber, TrapType tType */ );
  135. #else
  136.     void EventLoop( void );
  137.     void DoEvent( EventRecord *event );
  138.     void AdjustCursor( Point mouse, RgnHandle region );
  139.     void DoUpdate( WindowPtr window );
  140.     void DoActivate( WindowPtr window, Boolean becomingActive );
  141.     void DoContentClick( WindowPtr window );
  142.     void DrawWindow( WindowPtr window );
  143.     void AdjustMenus( void );
  144.     void DoMenuCommand( long menuResult );
  145.     void SetLight( WindowPtr window, Boolean newStopped );
  146.     void DoCloseWindow( WindowPtr window );
  147.     void DoCloseBehind( WindowPtr window );
  148.     void Terminate( void );
  149.     void Initialize( void );
  150.     void GoGetRect( short rectID, Rect *theRect );
  151.     void ForceEnvirons( void );
  152.     Boolean IsAppWindow( WindowPtr window );
  153.     Boolean IsDAWindow( WindowPtr window );
  154.     Boolean TrapAvailable( short tNumber, TrapType tType );
  155. #endif
  156.  
  157.  
  158. /* Make the 2.0 Interface for passing Points to the Toolbox by address,
  159.    emulate the 3.0 method of passing Points by value. This list only contains
  160.    the affected routines actually used in this sample, and is not intended to
  161.    be a comprehensive list of the affected routines.
  162.  
  163.    For routines that have Str255 formal parameters we cannot do a similar trick
  164.    so the necessary changes are in the code itself. Searching for MPW3 will find
  165.    them. */
  166. #ifndef MPW3
  167. #    define FindWindow    FINDWINDOW
  168. #    define MenuSelect    MENUSELECT
  169. #    define DragWindow    DRAGWINDOW
  170. #    define GrowWindow    GROWWINDOW
  171. #    define TrackBox        TRACKBOX
  172. #    define PtInRgn        PTINRGN
  173. #endif
  174.  
  175. /* Define HiWrd and LoWrd macros for efficiency. */
  176. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  177. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  178.  
  179. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  180.    dependency on the ordering of fields within a Rect */
  181. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  182. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  183.  
  184.  
  185. extern void _DataInit();
  186.  
  187. /* This routine is part of the MPW runtime library. This external
  188.    reference to it is done so that we can unload its segment, %A5Init. */
  189.  
  190.  
  191. #define __SEG__ Main
  192. main()
  193. {
  194.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  195.     ForceEnvirons();                /* check for some basic requirements; exits if not met */
  196.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  197.  
  198.     Initialize();                    /* initialize the program */
  199.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  200.  
  201.     EventLoop();                    /* call the main event loop */
  202. }
  203.  
  204.  
  205. /*    Get events forever, and handle them by calling DoEvent.
  206.     Get the events by calling WaitNextEvent, if it's available, otherwise
  207.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  208.  
  209. #define __SEG__ Main
  210. void EventLoop()
  211. {
  212.     RgnHandle    cursorRgn;
  213.     Boolean        gotEvent;
  214.     EventRecord    event;
  215.  
  216.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  217.     do {
  218.         /* use WNE if it is available */
  219.         if ( gHasWaitNextEvent )
  220.             gotEvent = WaitNextEvent(everyEvent, &event, MAXLONG, cursorRgn);
  221.         else {
  222.             SystemTask();
  223.             gotEvent = GetNextEvent(everyEvent, &event);
  224.         }
  225.         if ( gotEvent ) {
  226.             /* make sure we have the right cursor before handling the event */
  227.             AdjustCursor(event.where, cursorRgn);
  228.             DoEvent(&event);
  229.         }
  230.         /* change the cursor (and region) if necessary */
  231.         AdjustCursor(event.where, cursorRgn);
  232.     } while ( true );    /* loop forever; we quit via ExitToShell */
  233. } /*EventLoop*/
  234.  
  235.  
  236. /* Do the right thing for an event. Determine what kind of event it is, and call
  237.  the appropriate routines. */
  238.  
  239. #define __SEG__ Main
  240. void DoEvent(event)
  241.     EventRecord    *event;
  242. {
  243.     short        part;
  244.     WindowPtr    window;
  245.     Boolean        hit;
  246.     char        key;
  247.  
  248.     switch ( event->what ) {
  249.         case mouseDown:
  250.             part = FindWindow(event->where, &window);
  251.             switch ( part ) {
  252.                 case inMenuBar:                /* process a mouse menu command (if any) */
  253.                     AdjustMenus();
  254.                     DoMenuCommand(MenuSelect(event->where));
  255.                     break;
  256.                 case inSysWindow:            /* let the system handle the mouseDown */
  257.                     SystemClick(event, window);
  258.                     break;
  259.                 case inContent:
  260.                     if ( window != FrontWindow() ) {
  261.                         SelectWindow(window);
  262.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  263.                     } else
  264.                         DoContentClick(window);
  265.                     break;
  266.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  267.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  268.                     break;
  269.                 case inGrow:
  270.                     break;
  271.                 case inZoomIn:
  272.                 case inZoomOut:
  273.                     hit = TrackBox(window, event->where, part);
  274.                     if ( hit ) {
  275.                         SetPort(window);                /* the window must be the current port... */
  276.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  277.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  278.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  279.                     }
  280.                     break;
  281.             }
  282.             break;
  283.         case keyDown:
  284.         case autoKey:                        /* check for menukey equivalents */
  285.             key = event->message & charCodeMask;
  286.             if ( event->modifiers & cmdKey )            /* Command key down */
  287.                 if ( event->what == keyDown ) {
  288.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  289.                     DoMenuCommand(MenuKey(key));
  290.                 }
  291.             break;
  292.         case activateEvt:
  293.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  294.             break;
  295.         case updateEvt:
  296.             DoUpdate((WindowPtr) event->message);
  297.             break;
  298.         case osEvent:
  299.             switch (event->message >> 24) {             /* high byte of message */
  300.                 case suspendResumeMessage:                /* suspend/resume is also an activate/deactivate */
  301.                     gInBackground = (event->message & resumeMask) == 0;
  302.                     DoActivate(FrontWindow(), !gInBackground);
  303.                     break;
  304.             }
  305.             break;
  306.     }
  307. } /*DoEvent*/
  308.  
  309.  
  310. /*    Change the cursor's shape, depending on its position. This also calculates the region
  311.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  312.     that region, an event would be generated, causing this routine to be called,
  313.     allowing us to change the region to the region the mouse is currently in. If
  314.     there is more to the event than just “the mouse moved”, we get called before the
  315.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  316.     this is called again before we fall back into WNE. */
  317.  
  318. #define __SEG__ Main
  319. void AdjustCursor(mouse,region)
  320.     Point        mouse;
  321.     RgnHandle    region;
  322. {
  323.     WindowPtr    window;
  324.     RgnHandle    arrowRgn;
  325.     RgnHandle    plusRgn;
  326.     Rect        globalPortRect;
  327.  
  328.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  329.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  330.         /* calculate regions for different cursor shapes */
  331.         arrowRgn = NewRgn();
  332.         plusRgn = NewRgn();
  333.  
  334.         /* start with a big, big rectangular region */
  335.         SetRectRgn(arrowRgn, extremeNeg, extremeNeg, extremePos, extremePos);
  336.  
  337.         /* calculate plusRgn */
  338.         if ( IsAppWindow(window) ) {
  339.             SetPort(window);    /* make a global version of the viewRect */
  340.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  341.             globalPortRect = window->portRect;
  342.             RectRgn(plusRgn, &globalPortRect);
  343.             SectRgn(plusRgn, window->visRgn, plusRgn);
  344.             SetOrigin(0, 0);
  345.         }
  346.  
  347.         /* subtract other regions from arrowRgn */
  348.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  349.  
  350.         /* change the cursor and the region parameter */
  351.         if ( PtInRgn(mouse, plusRgn) ) {
  352.             SetCursor(*GetCursor(plusCursor));
  353.             CopyRgn(plusRgn, region);
  354.         } else {
  355.             SetCursor(&qd.arrow);
  356.             CopyRgn(arrowRgn, region);
  357.         }
  358.  
  359.         /* get rid of our local regions */
  360.         DisposeRgn(arrowRgn);
  361.         DisposeRgn(plusRgn);
  362.     }
  363. } /*AdjustCursor*/
  364.  
  365.  
  366. /*    This is called when an update event is received for a window.
  367.     It calls DrawWindow to draw the contents of an application window.
  368.     As an effeciency measure that does not have to be followed, it
  369.     calls the drawing routine only if the visRgn is non-empty. This
  370.     will handle situations where calculations for drawing or drawing
  371.     itself is very time-consuming. */
  372.  
  373. #define __SEG__ Main
  374. void DoUpdate(window)
  375.     WindowPtr    window;
  376. {
  377.     if ( IsAppWindow(window) ) {
  378.         BeginUpdate(window);                /* this sets up the visRgn */
  379.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  380.             DrawWindow(window);
  381.         EndUpdate(window);
  382.     }
  383. } /*DoUpdate*/
  384.  
  385.  
  386. /*    This is called when a window is activated or deactivated.
  387.     In Sample, the Window Manager's handling of activate and
  388.     deactivate events is sufficient. Other applications may have
  389.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  390.  
  391. #define __SEG__ Main
  392. void DoActivate(window, becomingActive)
  393.     WindowPtr    window;
  394.     Boolean        becomingActive;
  395. {
  396.     if ( IsAppWindow(window) ) {
  397.         if ( becomingActive )
  398.             /* do whatever you need to at activation */ ;
  399.         else
  400.             /* do whatever you need to at deactivation */ ;
  401.     }
  402. } /*DoActivate*/
  403.  
  404.  
  405. /*    This is called when a mouse-down event occurs in the content of a window.
  406.     Other applications might want to call FindControl, TEClick, etc., to
  407.     further process the click. */
  408.  
  409. #define __SEG__ Main
  410. void DoContentClick(window)
  411.     WindowPtr    window;
  412. {
  413.     SetLight(window, ! gStopped);
  414. } /*DoContentClick*/
  415.  
  416.  
  417. /* Draw the contents of the application window. We do some drawing in color, using
  418.    Classic QuickDraw's color capabilities. This will be black and white on old
  419.    machines, but color on color machines. At this point, the window’s visRgn
  420.    is set to allow drawing only where it needs to be done. */
  421.  
  422. #define __SEG__ Main
  423. void DrawWindow(window)
  424.     WindowPtr    window;
  425. {
  426.     SetPort(window);
  427.  
  428.     EraseRect(&window->portRect);    /* clear out any garbage that may linger */
  429.     if ( gStopped )                    /* draw a red (or white) stop light */
  430.         ForeColor(redColor);
  431.     else
  432.         ForeColor(whiteColor);
  433.     PaintOval(&gStopRect);
  434.     ForeColor(blackColor);
  435.     FrameOval(&gStopRect);
  436.     if ( ! gStopped )                /* draw a green (or white) go light */
  437.         ForeColor(greenColor);
  438.     else
  439.         ForeColor(whiteColor);
  440.     PaintOval(&gGoRect);
  441.     ForeColor(blackColor);
  442.     FrameOval(&gGoRect);
  443. } /*DrawWindow*/
  444.  
  445.  
  446. /*    Enable and disable menus based on the current state.
  447.     The user can only select enabled menu items. We set up all the menu items
  448.     before calling MenuSelect or MenuKey, since these are the only times that
  449.     a menu item can be selected. Note that MenuSelect is also the only time
  450.     the user will see menu items. This approach to deciding what enable/
  451.     disable state a menu item has the advantage of concentrating all
  452.     the decision-making in one routine, as opposed to being spread throughout
  453.     the application. Other application designs may take a different approach
  454.     that is just as valid. */
  455.  
  456. #define __SEG__ Main
  457. void AdjustMenus()
  458. {
  459.     WindowPtr    window;
  460.     MenuHandle    menu;
  461.  
  462.     window = FrontWindow();
  463.  
  464.     menu = GetMHandle(mFile);
  465.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  466.         EnableItem(menu, iClose);
  467.     else
  468.         DisableItem(menu, iClose);    /* but not our traffic light window */
  469.  
  470.     menu = GetMHandle(mEdit);
  471.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  472.         EnableItem(menu, iUndo);
  473.         EnableItem(menu, iCut);
  474.         EnableItem(menu, iCopy);
  475.         EnableItem(menu, iClear);
  476.         EnableItem(menu, iPaste);
  477.     } else {                        /* …but we don’t use it */
  478.         DisableItem(menu, iUndo);
  479.         DisableItem(menu, iCut);
  480.         DisableItem(menu, iCopy);
  481.         DisableItem(menu, iClear);
  482.         DisableItem(menu, iPaste);
  483.     }
  484.  
  485.     menu = GetMHandle(mLight);
  486.     if ( IsAppWindow(window) ) {    /* we know that it must be the traffic light */
  487.         EnableItem(menu, iStop);
  488.         EnableItem(menu, iGo);
  489.     } else {
  490.         DisableItem(menu, iStop);
  491.         DisableItem(menu, iGo);
  492.     }
  493.     CheckItem(menu, iStop, gStopped); /* we can also determine check/uncheck state, too */
  494.     CheckItem(menu, iGo, ! gStopped);
  495. } /*AdjustMenus*/
  496.  
  497.  
  498. /*    This is called when an item is chosen from the menu bar (after calling
  499.     MenuSelect or MenuKey). It performs the right operation for each command.
  500.     It is good to have both the result of MenuSelect and MenuKey go to
  501.     one routine like this to keep everything organized. */
  502.  
  503. #define __SEG__ Main
  504. void DoMenuCommand(menuResult)
  505.     long        menuResult;
  506. {
  507.     short        menuID;                /* the resource ID of the selected menu */
  508.     short        menuItem;            /* the item number of the selected menu */
  509.     short        itemHit;
  510.     Str255        daName;
  511.     short        daRefNum;
  512.     Boolean        handledByDA;
  513.  
  514.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  515.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  516.     switch ( menuID ) {
  517.         case mApple:
  518.             switch ( menuItem ) {
  519.                 case iAbout:        /* bring up alert for About */
  520.                     itemHit = Alert(rAboutAlert, nil);
  521.                     break;
  522.                 default:            /* all non-About items in this menu are DAs */
  523. #                    ifndef MPW3
  524.                         /* type Str255 is a struct in MPW 2 */
  525.                         GETITEM(GetMHandle(mApple), menuItem, &daName);
  526.                         daRefNum = OPENDESKACC(&daName);
  527. #                    else
  528.                         /* type Str255 is an array in MPW 3 */
  529.                         GetItem(GetMHandle(mApple), menuItem, daName);
  530.                         daRefNum = OpenDeskAcc(daName);
  531. #                    endif
  532.                     break;
  533.             }
  534.             break;
  535.         case mFile:
  536.             switch ( menuItem ) {
  537.                 case iClose:
  538.                     DoCloseWindow(FrontWindow());
  539.                     break;
  540.                 case iQuit:
  541.                     Terminate();
  542.                     break;
  543.             }
  544.             break;
  545.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  546.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  547.             break;
  548.         case mLight:
  549.             switch ( menuItem ) {
  550.                 case iStop:
  551.                     SetLight(FrontWindow(), true);
  552.                     break;
  553.                 case iGo:
  554.                     SetLight(FrontWindow(), false);
  555.                     break;
  556.             }
  557.             break;
  558.     }
  559.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  560. } /*DoMenuCommand*/
  561.  
  562.  
  563. /* Change the setting of the light. */
  564.  
  565. #define __SEG__ Main
  566. void SetLight( window, newStopped )
  567.     WindowPtr    window;
  568.     Boolean        newStopped;
  569. {
  570.     if ( newStopped != gStopped ) {
  571.         gStopped = newStopped;
  572.         SetPort(window);
  573.         InvalRect(&window->portRect);
  574.     }
  575. } /*SetLight*/
  576.  
  577.  
  578. /*    Close a window. This handles only desk accessory windows because we do not
  579.     allow our window to be closed. TESample provides an example of how to handle
  580.     the closing of application windows. */
  581.  
  582. #define __SEG__ Main
  583. void DoCloseWindow(window)
  584.     WindowPtr    window;
  585. {
  586.     if ( IsDAWindow(window) )
  587.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  588. } /*DoCloseWindow*/
  589.  
  590.  
  591. /*    Close the window that is passed and all windows behind it.
  592.     This closes windows from back to front, by calling itself
  593.     recursively, which minimizes window updating. Always keep
  594.     in mind the dangers of stack overflow when recursive routines
  595.     are used in situations where the calling level gets too
  596.     deep. That is not a problem here. */
  597.  
  598. #define __SEG__ Main
  599. void DoCloseBehind(window)
  600.     WindowPtr    window;
  601. {
  602.     if ( window != nil ) {    /* if we are passed a window, close other windows behind it first */
  603.         DoCloseBehind((WindowPtr) (((WindowPeek) window)->nextWindow));
  604.         DoCloseWindow(window);    /* now that all the windows behind are closed, close this one */
  605.     }
  606. } /*DoCloseBehind*/
  607.  
  608.  
  609. /* Clean up the application and exits. We close all of the windows so that
  610.  they can update their documents, if any. */
  611.  
  612. #define __SEG__ Main
  613. void Terminate()
  614. {
  615.     DoCloseBehind(FrontWindow());    /* close all windows */
  616.     ExitToShell();
  617. } /*Terminate*/
  618.  
  619.  
  620. /* Set up the whole world, including global variables, Toolbox managers,
  621.  and menus. We also create our one application window at this time.
  622.  Since window storage is non-relocateable, how and when to allocate space
  623.  for windows is very important so that heap fragmentation does not occur.
  624.  Because Sample has only one window and it is only disposed when the application
  625.  quits, we will allocate its space here, before anything that might be a locked
  626.  relocatable object gets into the heap. This way, we can force the storage to be
  627.  in the lowest memory available in the heap. Window storage can differ widely
  628.  amongst applications depending on how many windows are created and disposed.
  629.  If a failure occurs here, we will assume that the application is in such
  630.  bad shape that we should just exit. Your error handling may differ, but
  631.  the checks should still be made. */
  632.  
  633. #define __SEG__ Initialize
  634. void Initialize()
  635. {
  636.     Handle        menuBar;
  637.     WindowPtr    window;
  638.  
  639.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  640.     gInBackground = false;
  641.  
  642.     InitGraf((Ptr) &qd.thePort);
  643.     InitFonts();
  644.     InitWindows();
  645.     InitMenus();
  646.     TEInit();
  647.     InitDialogs(nil);
  648.     InitCursor();
  649.     
  650. /*     we will allocate our own window storage instead of letting the Window
  651.     Manager do it because GetNewWindow may load in temp. resources before
  652.     making the NewPtr call, and this can lead to heap fragmentation. */
  653.     window = (WindowPtr) NewPtr(sizeof(WindowRecord));
  654.     if ( window == nil ) ExitToShell();
  655.     window = GetNewWindow(rWindow, (Ptr) window, (WindowPtr) -1);
  656.  
  657.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  658.     if ( menuBar == nil ) ExitToShell();
  659.     SetMenuBar(menuBar);                    /* install menus */
  660.     DisposHandle(menuBar);
  661.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  662.     DrawMenuBar();
  663.     
  664.     gStopped = true;
  665.     GoGetRect(rStopRect, &gStopRect);        /* the stop light rectangle */
  666.     GoGetRect(rGoRect, &gGoRect);            /* the go light rectangle */
  667. } /*Initialize*/
  668.  
  669.  
  670. /*    This utility loads the global rectangles that are used by the window
  671.     drawing routines. It shows how the resource manager can be used to hold
  672.     values in a convenient manner. These values are then easily altered without
  673.     having to re-compile the source code. In this particular case, we know
  674.     that this routine is being called at initialization time. Therefore,
  675.     if a failure occurs here, we will assume that the application is in such
  676.     bad shape that we should just exit. Your error handling may differ, but
  677.     the check should still be made. */
  678.     
  679. #define __SEG__ Initialize
  680. void GoGetRect( short rectID, Rect *theRect )
  681. {
  682.     Handle        resource;
  683.     
  684.     resource = GetResource('RECT', rectID);
  685.     if ( resource == nil ) ExitToShell();
  686.     *theRect = **((Rect**) resource);
  687. } /* GoGetRect */
  688.  
  689.  
  690. /*    Make sure that the machine has at least 128K ROMs and enough memory to run.
  691.     If it doesn't, exit. SysEnvirons can be called before the toolbox managers
  692.     are initialized, and we need to call it at this point so we can check for
  693.     the right ROMs and memory availability before we call MaxApplZone and
  694.     initialize the toolbox managers. If AppleTalk has not been initialized, you
  695.     won't get the version of the AppleTalk driver that is running. That is not
  696.     critical here, and if that information was required, SysEnvirons could be
  697.     called again after AppleTalk had been initialized. */
  698.  
  699. #define __SEG__ Main
  700. void ForceEnvirons()
  701. {
  702.     OSErr    ignoreError;
  703.  
  704.     /* ignore the error returned from SysEnvirons; even if an error occurred,
  705.        the SysEnvirons glue will fill in the SysEnvRec */
  706.     ignoreError = SysEnvirons(sysEnvironsVersion, &gMac);
  707.     if ( (gMac.machineType < 0) ||
  708.         (StackSpace() + (long) GetApplLimit() - (long) ApplicZone() < kMinSize * 1024) )
  709.         ExitToShell();
  710.     /* if you have stack requirements that differ from the default,
  711.        then you could use SetApplLimit to increase StackSpace at this point. */
  712. } /* ForceEnvirons */
  713.  
  714.  
  715. /*    Check to see if a window belongs to the application. If the window pointer
  716.     passed was NIL, then it could not be an application window. WindowKinds
  717.     that are negative belong to the system and windowKinds less than userKind
  718.     are reserved by Apple except for windowKinds equal to dialogKind, which
  719.     mean it is a dialog. */
  720.  
  721. #define __SEG__ Main
  722. Boolean IsAppWindow(window)
  723.     WindowPtr    window;
  724. {
  725.     short        windowKind;
  726.  
  727.     if ( window == nil )
  728.         return false;
  729.     else {    /* application windows have windowKinds >= userKind (8) or dialogKind (2) */
  730.         windowKind = ((WindowPeek) window)->windowKind;
  731.         return (windowKind >= userKind) || (windowKind == dialogKind);
  732.     }
  733. } /*IsAppWindow*/
  734.  
  735.  
  736. /* Check to see if a window belongs to a desk accessory. */
  737.  
  738. #define __SEG__ Main
  739. Boolean IsDAWindow(window)
  740.     WindowPtr    window;
  741. {
  742.     if ( window == nil )
  743.         return false;
  744.     else    /* DA windows have negative windowKinds */
  745.         return ((WindowPeek) window)->windowKind < 0;
  746. } /*IsDAWindow*/
  747.  
  748.  
  749. /*    Check to see if a given trap is implemented. This is only used by the
  750.     Initialize routine in this program, so we put it in the Initialize segment.
  751.     The recommended approach to see if a trap is implemented is to see if
  752.     the address of the trap routine is the same as the address of the
  753.     Unimplemented trap. */
  754.  
  755. #define __SEG__ Initialize
  756. Boolean TrapAvailable(tNumber,tType)
  757.     short        tNumber;
  758.     TrapType    tType;
  759. {
  760.     /* Check and see if the trap exists. On 64K ROM machines, tType will be ignored. */
  761.  
  762.     return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
  763. } /*TrapAvailable*/
  764.